<?php


namespace app\common\service;


use dh2y\qrcode\QRcode;
use QRcode as QRcodeThink;

class QRcodeService extends QRcode
{
    public static function init()
    {
        return new static();
    }

    /**
     * 添加logo到二维码中
     * @param $logo
     * @return bool|mixed
     */
    public function logo($logo)
    {
        if (!isset($logo) || $logo == '') {
            $this->error = 'logo不存在';
            return false;
        }
        $QR = imagecreatefromstring(file_get_contents($this->outfile));
        $logo = imagecreatefromstring(file_get_contents($logo));
        $QR_width = imagesx($QR);//二维码图片宽度
//        $QR_height = imagesy($QR);//二维码图片高度
        $logo_width = imagesx($logo);//logo图片宽度
        $logo_height = imagesy($logo);//logo图片高度
        $logo_qr_width = $QR_width / 3;
        $scale = $logo_width / $logo_qr_width;
        $logo_qr_height = $logo_height / $scale;
        $from_width = ($QR_width - $logo_qr_width) / 2;
        //重新组合图片并调整大小
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);

        $this->outfile = $this->cache_dir . '/' . time() . '.png';
        imagepng($QR, $this->outfile);
        imagedestroy($QR);
        return $this;
    }


    /**
     * 生成普通二维码
     * @param string $url 生成url地址
     * @param bool $outfile
     * @param int $size
     * @param string $evel
     * @return $this
     */
    public function png($url, $outfile = false, $size = 5, $evel = 'H')
    {

        if (!$outfile) {
            $outfile = $this->cache_dir . '/' . time() . '.png';
        }

        $this->outfile = $outfile;

        QRcodeThink::png($url, $outfile, $evel, $size, 2);
        return $this;
    }

}